require("./index.scss");
var STip = ZFT.Util.STip;
var Ajax = ZFT.Util.Ajax;
var ParseTemplate = ZFT.Util.ParseTemplate;
var Pagination = require("COMMON/modules/pagination-x/v1.0/");
var Template = {
    list: ParseTemplate(require("./tpl/list.xtpl")),
    tr: ParseTemplate(require("./tpl/tr.xtpl"))
}
var Main = ZFT.Util.Class({
    container: $("body"),
    EVENTS: {
        "click #payType .u-type_item": "toggleType",
        "click #dateBox .u-date_item": "toggleDateControl",
        "click #expBtn,#getKeyWord": "selectAndExport",
        "change #key": "toggleSearchTip"
    },
    init: function () {
        var _this = this;
        _this.initDate();
        _this.getTargetDate("3");
        _this.getBuildingList();
        _this.selectAndExport($("#getKeyWord"), 1);
        //初始化分页
        var pagination = this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, toPage: toPage }),
                _this.selectAndExport($("#getKeyWord"), toPage);
        })
    },
    initDate: function () {
        $("#beginDate").datepicker({
            format: "yyyy-mm-dd",
            maxViewMode: 2,
            language: "zh-CN",
            // todayBtn: "linked",
            autoclose: true,

        });
        $("#endDate").datepicker({
            format: "yyyy-mm-dd",
            maxViewMode: 2,
            language: "zh-CN",
            //todayBtn: "linked",
            autoclose: true,
        });

    },
    toggleType: function (e) {
        var tarBtn = $(e.currentTarget);
        if (tarBtn.hasClass("checked")) return false;
        tarBtn.addClass("checked").siblings().removeClass("checked");
    },
    toggleDateControl: function (e) {
        var _this = this;
        var tarBtn = $(e.currentTarget);
        var tarType = tarBtn.attr("data-type"); //1清空 2昨天 3今天 4本周 5上周 6本月 7上月
        var targetDate, beginDate, endDate;
        tarBtn.addClass("checked").siblings().removeClass("checked");
        _this.getTargetDate(tarType);
    },
    getTargetDate: function (type) {
        //1清空 2昨天 3今天 4本周 5上周 6本月 7上月
        var _this = this;
        var now = new Date(); //获取当前日期
        var nowDayOfWeek = now.getDay(); //获取本周第几天
        var nowDay = now.getDate(); //获取当前日
        var lastDay = now.getDate();//获取昨天
        var nowMonth = now.getMonth(); //获取当前月
        var nowYear = now.getFullYear(); //获取当前年
        var lastMonthDate = new Date();//上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getFullYear();
        var lastMonth = lastMonthDate.getMonth();
        var today = _this.formatDate(new Date(nowYear, nowMonth, nowDay));
        var yesterday = _this.formatDate(new Date(nowYear, nowMonth, lastDay - 1));
        var weekBegin = _this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1));
        var weekEnd = _this.formatDate(new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 1));
        var lastWeekBegin = _this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7 + 1));
        var lastWeekEnd = _this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1 + 1))
        var monthBegin = _this.formatDate(new Date(nowYear, nowMonth, 1));
        var monthEnd = _this.formatDate(new Date(nowYear, nowMonth, _this.getMonthDays(nowMonth)));
        var lastMonthBegin = _this.formatDate(new Date(lastYear, lastMonth, 1));
        var lastMonthEnd = _this.formatDate(new Date(lastYear, lastMonth, _this.getMonthDays(lastMonth)));
        var tarDate, beginDate, endDate;
        switch (type) {
            case "1":
                tarDate = {
                    beginDate: "",
                    endDate: ""
                }
                break;
            case "2":
                tarDate = {
                    beginDate: yesterday,
                    endDate: yesterday
                }
                break;
            case "3":
                tarDate = {
                    beginDate: today,
                    endDate: today
                }
                break;
            case "4":
                tarDate = {
                    beginDate: weekBegin,
                    endDate: weekEnd
                };
                break;
            case "5":
                tarDate = {
                    beginDate: lastWeekBegin,
                    endDate: lastWeekEnd
                };
                break;
            case "6":
                tarDate = {
                    beginDate: monthBegin,
                    endDate: monthEnd
                };
                break;
            case "7":
                tarDate = {
                    beginDate: lastMonthBegin,
                    endDate: lastMonthEnd
                };
                break;
        }
        $(".u-date_item").off("click");
        $("#beginDate").val(tarDate.beginDate);
        $("#endDate").val(tarDate.endDate);
        //  console.log(tarDate)
    },
    formatDate: function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '-' + m + '-' + d;
    },
    getMonthDays: function (month) {
        var now = new Date();
        var nowYear = now.getFullYear(); //获取当前年
        var monthStartDate = new Date(nowYear, month, 1);
        var monthEndDate = new Date(nowYear, month + 1, 1);
        var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
    },
    selectAndExport: function (e, toPage) {
        var $this = $(e.currentTarget);
        var _this = this;
        var tarType = $this.attr("data-type");
        var page = $(".paginationWrap");
        var tbody = $("#tbody");
        if (!toPage) toPage = 1;
        var param = {
            begin_time: $.trim($("#beginDate").val()),
            end_time: $.trim($("#endDate").val()),
            fee_type: $("#feeType").val(),
            money_from: $("#sumUp").val(),
            money_to: $("#sumTo").val(),
            pay_type: $("#payType .u-type_item.checked").attr("data-type"),
            key: $("#key").val(),
            value: $("#keyInp").val(),
            page: toPage,
            page_size: page.attr("data-size"),
            excel: 0,
            building_id: $("#buildingName").val()
        };
        var regMoney = /^$|^(\d*\.)?\d+$/;
        if (!param["begin_time"] || !param["end_time"]) return STip("fail", "时间不为空！");
        if (!regMoney.test(param["money_from"]) || !regMoney.test(param["money_to"])) {
            return STip("fail", "请输入正确的金额！");
        }
        Ajax("/r/TradeRecord_getList", {
            type: "POST",
            dataType: "json",
            params: param,
            loading: function () {
                var loading = "<tr><td colspan='9'>正在加载，请稍后...</td></tr>";
                if (tarType != 1) {
                    page.hide();
                    tbody.html(loading);
                }
            },
            success: function (res) {

                if (res.code == 200) {
                    if (!tarType) {
                        var html = Template.list({ data: res.data.list });
                        tbody.html(html);
                        _this.pagination.render({ current: toPage, toPage: toPage, total: res.data.total });
                    } else {
                        var newWindow = window.open("about:blank", "_self");
                        URL = "/r/TradeRecord_getList?begin_time=" + param["begin_time"] + "&end_time=" + param["end_time"] + "&fee_type=" + param["fee_type"] + "&money_from=" + param["money_from"]
                            + "&money_to=" + param["money_to"] + "&key=" + param["key"] + "&value=" + param["value"] + "&building_id=" + param["building_id"] + "&page=" + param["page"] + "&excel=1";
                        newWindow.location = URL;
                        newWindow = null
                    }
                } else {
                    if (!tarType) {
                        var error = "<tr><td colspan='9'>" + res.msg + "</td></tr>";
                        tbody.html(error);
                    } else {
                        return STip("fail", res.msg);
                    }

                }

            }
        })



    },
    toggleSearchTip: function (e) {
        var tarVal = $(e.currentTarget).val();
        var name = "请输入对方名称";
        var room = "请输入房号";
        $("#keyInp").attr("placeholder", (tarVal == 1) ? name : room);
    },
    getBuildingList: function () {
        var _this = this;
        Ajax("/r/Building_getOwnerBuilding", {
            "type": "POST",
            "dataType": "json",
            success: function (res) {
                if (res.code == 200) {
                    var html,
                        data = res.data;
                    data["approvePer"] = ($.inArray("29", _this.pers) !== -1) ? 1 : 0;
                    html = Template.tr({ data: data });
                    $("#buildingName").html(html);
                } else {
                    STip("fail", res.msg);
                }
            }
        })
    }

})
$(function () {
    new Main();
})